package com.xingmang.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingmang.common.constant.PageEntity;
import com.xingmang.common.constant.ResponseData;
import com.xingmang.common.constant.ResultBean;
import com.xingmang.common.dto.admin.FieldSettingInfoDTO;
import com.xingmang.common.dto.admin.FieldSettingPageDTO;
import com.xingmang.common.dto.admin.FieldSettingSaveDTO;
import com.xingmang.common.dto.admin.FieldSettingUpdateDTO;
import com.xingmang.common.vo.admin.FieldSettingPageVO;
import com.xingmang.db.entity.FieldSetting;
import com.xingmang.db.service.FieldSettingDBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/6/21 14:21
 */
@Service
@Slf4j
public class FieldSettingService {

    @Resource
    private FieldSettingDBService fieldSettingDBService;

    public ResultBean<PageEntity<FieldSettingPageVO>> page(FieldSettingPageDTO dto) {
        Page<FieldSetting> page = fieldSettingDBService.page(new Page<>(dto.getPagenum(), dto.getPagesize()),
                new LambdaQueryWrapper<FieldSetting>()
                        .eq(StringUtils.isNotEmpty(dto.getFieldType()), FieldSetting::getFieldType, dto.getFieldType())
                        .like(StringUtils.isNotEmpty(dto.getFieldName()), FieldSetting::getFieldValue, dto.getFieldValue())
                        .eq(StringUtils.isNotEmpty(dto.getFieldValue()), FieldSetting::getFieldValue, dto.getFieldValue()));
        List<FieldSettingPageVO> collect = page.getRecords().stream().map(fieldSetting -> {
            FieldSettingPageVO vo = BeanUtil.copyProperties(fieldSetting, FieldSettingPageVO.class);
            return vo;
        }).collect(Collectors.toList());
        PageEntity<FieldSettingPageVO> pageEntity = new PageEntity<>();
        BeanUtil.copyProperties(page,pageEntity);
        pageEntity.setRecords(collect);
        return ResponseData.success(pageEntity);
    }

    public ResultBean save(FieldSettingSaveDTO dto) {
        FieldSetting fieldSetting = BeanUtil.copyProperties(dto, FieldSetting.class);
        fieldSettingDBService.save(fieldSetting);
        return ResponseData.success(null);
    }

    public ResultBean update(FieldSettingUpdateDTO dto) {
        FieldSetting fieldSetting = BeanUtil.copyProperties(dto, FieldSetting.class);
        fieldSetting.setId(dto.getFieldSettingId());
        fieldSettingDBService.updateById(fieldSetting);
        return ResponseData.success(null);
    }

    public ResultBean delete(FieldSettingInfoDTO dto) {
        fieldSettingDBService.removeById(dto.getFieldSettingId());
        return ResponseData.success(null);
    }
}
